package com.bw.lib_storage.db.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.bw.lib_storage.db.entity.History

@Dao
interface HistoryDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(history: History)

    @Insert
    suspend fun insertAll(vararg history: History)

    @Delete
    suspend fun deleteHistory(history: History)

    @Update
    suspend fun updateHistory(history: History)

    @Query("SELECT * FROM history ORDER BY last_play_time DESC")
    suspend fun getAllHistory(): List<History>

    @Query("SELECT * FROM history WHERE video_id = :videoId LIMIT 1")
    suspend fun getHistoryByVideoId(videoId: String): History?

    @Query("SELECT * FROM history WHERE title LIKE '%' || :title || '%' ORDER BY last_play_time DESC")
    suspend fun getHistoryByTitle(title: String): List<History>

    @Query("SELECT * FROM history WHERE user_id = :userId ORDER BY last_play_time DESC")
    suspend fun getHistoryByUserId(userId: String): List<History>

    @Query("SELECT * FROM history WHERE is_completed = 1 ORDER BY last_play_time DESC")
    suspend fun getCompletedHistory(): List<History>

    @Query("SELECT * FROM history WHERE is_completed = 0 ORDER BY last_play_time DESC")
    suspend fun getIncompleteHistory(): List<History>

    @Query("DELETE FROM history WHERE video_id = :videoId")
    suspend fun deleteByVideoId(videoId: String)

    @Query("DELETE FROM history WHERE user_id = :userId")
    suspend fun deleteByUserId(userId: String)

    @Query("DELETE FROM history")
    suspend fun deleteAllHistory()

    @Query("SELECT COUNT(*) FROM history")
    suspend fun getHistoryCount(): Int

    @Query("SELECT * FROM history ORDER BY last_play_time DESC LIMIT :limit")
    suspend fun getRecentHistory(limit: Int): List<History>
}